package cn.iocoder.aics.module.member.service.chathistory;

import cn.iocoder.aics.module.member.controller.app.chathistory.vo.CompletionRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.util.retry.Retry;

import javax.annotation.security.PermitAll;
import java.time.Duration;

@Service
@RequiredArgsConstructor
public class StreamService {
    private final WebClient deepseekWebClient;

    public Flux<String> streamCompletion(CompletionRequest request) {
        return deepseekWebClient.post()
                .uri("/chat/completions")
                .bodyValue(request)
                .accept(MediaType.TEXT_EVENT_STREAM) // 声明接受事件流
                .retrieve()
                .onStatus(HttpStatus::isError, response ->
                        response.bodyToMono(String.class)
                                .flatMap(error -> Mono.error(new  RuntimeException("API Error: " + error)))
                )
                .bodyToFlux(String.class)
                .timeout(Duration.ofSeconds(30))  // 超时控制
                .retryWhen(Retry.backoff(3,  Duration.ofSeconds(1)));  // 重试机制
    }
}